<script setup lang="tsx">
import { computed, ref, watch } from "vue";
import { $t } from "@/locales";
import { ApiSysCgTempletInput, ApiSysCgTempletOut, SyscgconfigApi, SyscgtempletApi } from "@/api-services";
import { useForm } from "@/hooks/common/form";
import { SimpleScrollbar } from "@sa/materials";
import { queryDone } from "@/utils/api";
import { feature, getAPI } from "@/axios-utils";
import { NetoKit } from "@/typings/neto";

defineOptions({
  name: "SysCgTempletOperateModal",
});

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();
type OperateType = UI.TableOperateType;

interface Props {
  /** the type of operation */
  operateType: OperateType;
  /** the edit row data */
  rowData?: ApiSysCgTempletOut | null;
}

const props = defineProps<Props>();


const visible = defineModel<boolean>("visible", {
  default: false,
});
const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: $t("page.codeGenerator.sysCgTemplet.add"),
    // addChild: $t("page.manage.menu.addChildMenu"),
    edit: $t("page.codeGenerator.sysCgTemplet.edit"),
  };
  return titles[props.operateType];
});

const { formRef, restoreValidation } = useForm();

type ModelType = NetoKit.IsNonNullable<ApiSysCgTempletInput>;
/**
 * 创建默认数据
 */
const createDefaultModel = () => {
  return {
    id: 0,
    templateName: "",
    outFileName: "",
    saveRelativeDirectory: "",
    templateContent: "",
    cgConfigId: 0
  }
}
const model = ref<ModelType>(createDefaultModel());


const configSelectItems = ref<any>([]);
function cloaseWindow() {
  visible.value = false;
}


async function handleSubmit() {

  // const input = ref<ApiSysCgTempletInput>({});
  //Object.assign(input.value,model.value)
  // input.value.cgConfigId = model.value.cgConfigId;
  // input.value.id = model.value.id;
  // input.value.templateName = model.value.templateName;
  // input.value.outFileName = model.value.outFileName;
  // input.value.saveRelativeDirectory = model.value.saveRelativeDirectory;
  // input.value.resourceFileName = model.value.resourceFileName;
  // input.value.templateContent = model.value.templateContent;


  if (props.operateType === "add") {
    const [err, res] = await feature(getAPI(SyscgtempletApi).insert(model.value));
    queryDone(err, async () => {
      if (res?.data.succeeded) {
        window.$message?.success($t('common.addSuccess'));
        emit('submitted');
        visible.value = false;
      }
    });
  } else if (props.operateType === "edit") {
    const [err, res] = await feature(getAPI(SyscgtempletApi).update(model.value));
    queryDone(err, async () => {
      if (res?.data.data) {
        window.$message?.success($t('common.updateSuccess'));
        emit('submitted');
        visible.value = false;
      }
    });
  }



}

async function GetConfigSelectItems() {
  const [err, res] = await feature(getAPI(SyscgconfigApi).getSelectItems());
  queryDone(err, () => {
    if (res?.data.data) {
      if (process.env.NODE_ENV === "development")
        console.log(res.data.data)
      configSelectItems.value = res.data.data.map(it => ({
        label: it.value,
        value: it.key
      }));
      //configSelectItems.value=res.data.data;
    }
  });
}

async function handleInitModel() {

  //回复默认数据
  model.value = createDefaultModel();

  if (process.env.NODE_ENV === "development") {
    console.log(props.operateType);
    console.log(props.operateType + ":" + props.rowData?.id);
  }

  // if (process.env.NODE_ENV === "development")
  //   console.log(props.operateType);
  // model = ref<ApiSysCgTempletOut>({});
  if (props.operateType === "edit") {

    const [err, res] = await feature(getAPI(SyscgtempletApi).get(props.rowData?.id as number));
    queryDone(err, () => {
      if (res?.data.data) {
        Object.assign(model.value, res.data.data);
      }
    });
  }
  GetConfigSelectItems();
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <NModal v-model:open="visible" :title="title" width="1000px">
    <SimpleScrollbar>
      <ElForm ref="formRef" :model="model" label-width="auto">
        <ElFormItem label="配置项" name="configId">
          <ElSelect v-model="model.cgConfigId" :options="configSelectItems"></ElSelect>
        </ElFormItem>
        <ElFormItem label="模板名称" name="templateName">
          <ElInput v-model="model.templateName"/>
        </ElFormItem>

        <ElFormItem label="输出文件名" name="outFileName">
          <ElInput v-model="model.outFileName"/>
        </ElFormItem>
        <ElFormItem label="保存相对目录" name="saveRelativeDirectory">
          <ElInput v-model="model.saveRelativeDirectory"/>
        </ElFormItem>
        <ElFormItem label="模板内容" name="templateContent">
          <ElInput type="textarea" v-model="model.templateContent" :rows="10"/>
        </ElFormItem>
      </ElForm>
    </SimpleScrollbar>
    <template #footer>
      <div class="flex justify-end">
        <ElButton @click="cloaseWindow">{{ $t("common.cancel") }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{
          $t("common.confirm")
        }}</ElButton>
      </div>
    </template>
  </NModal>
</template>

<style scoped></style>
